import java.util.ArrayList;
import java.util.Scanner;

/**
 * GameBoard
 *
 * @author Jiachi Zhu
 * @date 2024/04/21
 */
public class MainGame {
    public static ArrayList<Player> players = new ArrayList<>();
    public static int winningScore = 100;

    /**
     * The entry point of application.
     *
     * @param args the input arguments
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        boolean isGameEnd = false;
        System.out.println("Welcome to the game of Scribble!!!");
        do {
            displayMainMenu();
            // Get the selection
            int option;
            try {
                option = sc.nextInt();
            } catch (Exception e) {
                sc.nextLine();     //consume the "enter" behind option number
                System.out.println("Please enter the correct option!!");
                continue;
            }
            // Perform the selection
            switch (option) {
                case 1:
                    gameSetting();

                    if (!gameRunning()) {
                        isGameEnd = true;
                    }
                    break;
                case 2:
                    //To get the relevant data
                    boolean isLoad = true;
                    try {
                        SaveAndLoad sal = SaveAndLoad.loadGame();
                        GameBoard.board = sal.getBoard();
                        GameBoard.isEnterdBoard = sal.getIsEnterBoard();
                        players = sal.getPlayers();
                        GameBoard.firstWord = sal.isFirstWord();
                        GameBoard.initializeTypeBoard();
                    } catch (RuntimeException e) {
                        isLoad = false;
                        System.out.println("Cannot load the game, please check your file");
                    }
                    if (isLoad) {
                        if (!gameRunning()) {
                            isGameEnd = true;
                        }
                    }
                    break;
                case 0:
                    isGameEnd = true;
                    break;
                default:
                    System.out.println("Please enter the correct option!!");
                    break;
            }
        } while (!isGameEnd);
        System.out.println("The game is end");
    }

    /**
     * Display main menu.
     */
    public static void displayMainMenu() {
        System.out.println("=========  M E N U  ========");
        System.out.println("Start a new game     <-- 1");
        System.out.println("Load last game       <-- 2");
        System.out.println("Exit the game        <-- 0");
    }

    /**
     * Game setting.
     * set player's number, player's name, winning Score
     */
    public static void gameSetting() {
        Scanner input = new Scanner(System.in);


        GameBoard.initializeBoard();
        int playerNumber;
        while (true) {
            System.out.println("Please enter the number of players (2-4):");

            if (input.hasNextInt()) {
                playerNumber = input.nextInt();
                input.nextLine();

                if (playerNumber >= 2 && playerNumber <= 4) {
                    break;  // 玩家数是否在合法范围
                } else {
                    System.out.println("The number you have input is not valid. Please enter a number between 2 and 4.");
                }
            } else {
                System.out.println("That's not a number. Please enter a number between 2 and 4.");
                input.next();
            }
        }

        // Player name input and initialisation
        for (int i = 0; i < playerNumber; i++) {
            if (i == 0) {
                System.out.println("You are the glorious host, only you can save the game");
            }
            System.out.println("Enter player " + (i + 1) + "'s name:");
            String name = input.nextLine();
            Player player = new Player(name, 0);
            players.add(player);
        }


        System.out.println("Please enter the winning score (minimum score should be 10):");
        while (true) {
            if (input.hasNextInt()) {
                winningScore = input.nextInt();
                if (winningScore >= 10) {
                    break; // Winning score within legal limits
                } else {
                    System.out.println("Winning score must be at least 10. Please enter a valid score.");
                }
            } else {
                System.out.println("That's not a valid number. Please enter an integer.");
                input.next();
            }
        }
        input.nextLine();
    }

    /**
     * Game running
     *
     * @return is the game running
     */
    public static boolean gameRunning() {
        Scanner sc = new Scanner(System.in);
        int currentPlayerIndex = 0;
        while (true) {
            Player currentPlayer = players.get(currentPlayerIndex);
            displayAllScore();
            GameBoard.printBoard();
            if (currentPlayerIndex == 0) {
                System.out.println("You can save the game by using -1.(if you don't want, Please input something real to continue)");
                if (sc.next().equals("-1")) {
                    char[][] currentBoard = GameBoard.printBoard();
                    char[][] currentEnterBoard = GameBoard.enteredLetterBoard;
                    boolean[][] currentIsEnteredBoard = GameBoard.isEnterdBoard;
                    ArrayList<Player> currentPlayers = new ArrayList<>();
                    currentPlayers.addAll(players);
                    //ArrayList<Player> currentPlayers = players;
                    boolean currentIsFirstWord = GameBoard.firstWord;
                    SaveAndLoad.saveGame(currentBoard, currentEnterBoard, currentIsEnteredBoard, currentPlayers, currentIsFirstWord);
                }
            }

            currentPlayer.takeTurn();

            if (currentPlayer.hasWon()) {
                System.out.println(currentPlayer.getName() + " wins the game!");
                //gameRunning = false;
                break;
            }

            // Move to the next player
            currentPlayerIndex = (currentPlayerIndex + 1) % players.size();
        }
        System.out.println("Game over.");
        return false;
    }

    /**
     * Display all palyer's score.
     */
    public static void displayAllScore() {
        int currentPlayerIndex = 0;
        System.out.println("=======  Score   Board  =======");
        while (currentPlayerIndex < players.size()) {
            Player currentPlayer = players.get(currentPlayerIndex);
            String name = currentPlayer.getName();
            int playerScore = currentPlayer.getPlayerScore();
            System.out.println(name + "\t\t" + playerScore);
            currentPlayerIndex += 1;
        }
    }
}